﻿using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
using Z.EntityFramework.Plus;

namespace OpenPasteSpider
{
    /// <summary>
    /// 回收服务
    /// </summary>
    public class RecoveryTaskHandler : ISingletonDependency
    {
        //private System.Timers.Timer _timer;
        private readonly IServiceProvider _serviceProvider;
        private SpiderConfig _config;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="setting"></param>
        public RecoveryTaskHandler(IServiceProvider serviceProvider, IOptions<SpiderConfig> setting)
        {
            _serviceProvider = serviceProvider;
            _config = setting.Value;
        }

        private int LastDay = -1;

        /// <summary>
        /// 
        /// </summary>
        public async void DoRecoveryAsync()
        {
            var daynow = DateTime.Now;
            if (daynow.Day != LastDay)
            {
                using var scope = _serviceProvider.CreateScope();
                using var _dbContext = scope.ServiceProvider.GetRequiredService<IOpenPasteSpiderDbContext>();

                var selectday = daynow.AddDays((0 - _config.RecoveryDay));

                //计划任务的日志记录
                _dbContext.PlanItem.Where(x => x.CreateDate < selectday).Delete();
                //发送警告记录
                await _dbContext.NoticeLog.Where(x => x.CreateDate < selectday).DeleteAsync();

                _dbContext.Dispose();
                scope.Dispose();
            }
        }

        //这个是否要预留给日统计

    }
}
